package com.lry.sso.service.ddd.service.impl;

import com.lry.sso.common.exception.SysInvocationException;
import com.lry.sso.common.util.captcha.Captcha;
import com.lry.sso.common.util.captcha.CaptchaBuilder;
import com.lry.sso.service.ddd.service.CaptchaService;
import com.lry.sso.service.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 验证码接口实现
 *
 * @author 李瑞益
 * @date 2019/9/4
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    private static final Logger logger = LoggerFactory.getLogger(CaptchaServiceImpl.class);

    @Autowired
    private RedisService redisService;

    @Override
    public Captcha getAndSaveCaptcha() {
        Captcha captcha = CaptchaBuilder.buildCaptcha();
        redisService.set(captcha.getCaptchasId(), captcha.getText(),120);
        logger.info("获取到验证码并缓存成功");
        return captcha;
    }

    @Override
    public boolean validCaptcha(String captchaId,String captchaCode) {
        if (StringUtils.isEmpty(captchaId)) {
            logger.info("验证码验证失败；验证码id为空");
            throw new SysInvocationException(LoginError.CAPTCHA_ERROR);
        }
        boolean isOk = true;
        Boolean isExist = redisService.exists(captchaId);
        if (!isExist) {
            logger.debug("验证码过期");
            throw new SysInvocationException(LoginError.CAPTCHA_EXPIRE.getCode(),"验证码过期，已刷新，请重新输入");
        }
        String text = redisService.get(captchaId);
        isOk = !StringUtils.isEmpty(text);
        logger.info("输入的验证码：{}，正确的验证码：{}",captchaCode,text);
        if (!captchaCode.equalsIgnoreCase(text)) {
            isOk = false;
        }
        return isOk;
    }

    @Override
    public void deleteCaptcha(String captchaId) {
        redisService.delete(captchaId);
        logger.info("删除验证码缓存成功！");
    }
}
